# Create your views here.
from django.views import View

from model.models import User
from server.utils import Request, Response, Code, Verify


class RegisterView(View):
    """ User register view """

    @Request.getJson
    def post(self, request):
        username = request.JSON.get('username')
        password = request.JSON.get('password')

        for code in [Verify.username(username), Verify.password(password)]:
            if code != Code.OK:
                return Response.Json(code=code)

        if User.objects.filter(username=username).exists():
            return Response.Json(code=Code.Error, msg="The username has already been registered")

        user = User(username=username, role=User.Role.person)
        user.set_password(password)
        user.save()
        return Response.Json(msg="Account registration successful")
